import { Component, OnInit } from '@angular/core';
import { StoreService } from '../store.service';
import { DataService } from '../data.service';
import { QueryPackage, Query, Aggregation, Condition } from '../classes';
import { query } from '@angular/animations';

@Component({
  selector: 'app-model',
  templateUrl: './model.component.html',
  styleUrls: ['./model.component.less'],
})
export class ModelComponent implements OnInit {
  constructor(
    public storeService: StoreService,
    public dataService: DataService
  ) {}

  ngOnInit() {}

  public async load() {
    let username = this.storeService.loginUser.UserName;
    if (!this.storeService.Authorize) username = undefined;
    let rl = await this.dataService.getModel(
      username,
      undefined,
      undefined,
      undefined,
      undefined
    );
    for (let index = 0; index < rl.length; index++) {
      const element = rl[index];
      element['publicCondition'] = this.dataService.getPublicCondition(element);
      element['version'] = this.dataService.getPackageVersion(element);
    }
    this.storeService.modelList = rl;
  }
  isExecute = false;

  public async execute(item: QueryPackage) {
    if (item.running) {
      alert('正在运行中，请稍等...');
      return;
    }
    item.running = true;
    if (this.dataService.isQuery(item)) {
      let query = this.dataService.getQueryObject(item) as Query;
      this.dataService.UpdatePublicConditionsForQuery(
        query,
        item.publicCondition
      );
      let r = await this.dataService.search(
        'mr',
        query,
        [],
        1,
        100000000,
        false
      );

      let ro = JSON.parse(r as string);
      item.result = ro['body'];
    }
    if (this.dataService.isAggregation(item)) {
      let agg = this.dataService.getQueryObject(item) as Aggregation;
      this.dataService.UpdatePublicConditionsForAggregation(
        agg,
        item.publicCondition
      );
      let r = await this.dataService.aggregate('mr', agg, true, false);
      item.result = {};
      item.result['statisticResult'] = this.flat(r['statisticResult']);
      item.result['combined'] = r['combined'];
    }
    item.running = false;
  }

  flat(collection: any[]): string[] {
    if (collection === undefined) return [];
    let rs: string[] = [];
    for (let v of collection) {
      console.log(v);
      let r = this.flatObject(v);
      console.log(r);
      rs = [...rs, ...r];
    }
    return rs;
  }

  flatObject(obj): string[] {
    let rs: string[] = [];
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        const element = obj[key];
        if (this.isObject(element)) {
          let or = this.flatObject(element);

          or.forEach((x) => {
            console.log(key + '.' + x);
            rs.push(key + '.' + x);
          });
        } else {
          let rstring = key + ':' + element.toString();

          rs.push(rstring);
        }
      }
    }
    return rs;
  }
  isObject(obj) {
    return obj instanceof Object;
  }

  public async open(item: QueryPackage) {
    if (this.dataService.isQuery(item)) {
      let q = this.dataService.getQueryObject(item) as Query;
      if (q.version === undefined || q.version < 2)
        this.dataService.CompatibilityQuery(q);
      this.storeService.query = q;
      this.storeService.actionType = 'query';
      console.log(this.storeService.query);
    }
    if (this.dataService.isAggregation(item)) {
      this.storeService.aggregation = this.dataService.cloneAggregation(
        this.dataService.getQueryObject(item) as Aggregation
      );

      this.storeService.actionType = 'agg';
    }
  }
  selectAnddeletePackage: any;
  confirmDelete: boolean = false;
  public async deletePackage() {
    if (this.selectAnddeletePackage != undefined) {
      await this.dataService.deleteModel(this.selectAnddeletePackage);
      this.storeService.modelList.splice(
        this.storeService.modelList.indexOf(this.selectAnddeletePackage),
        1
      );
    }
    this.selectAnddeletePackage = undefined;
    this.confirmDelete = false;
  }
  public async delete(item: QueryPackage) {
    this.selectAnddeletePackage = item;
    this.confirmDelete = true;
    // await this.dataService.deleteModel(item);
    // this.storeService.modelList.splice(
    //   this.storeService.modelList.indexOf(item),
    //   1
    // );
  }

  currentitem: Condition;
  showselect: boolean = false;
  valueDic = {};
  dic: any[] = [];
  selectitemValue = [];
  currentShowColumn = [];
  async openselect(item: Condition) {
    this.currentitem = item;
    this.currentShowColumn = item.DicColumns.split(',');
    console.log(this.currentShowColumn);
    this.showselect = true;
    console.log('load dic');
    this.dic = [];
    if (item.Options.length > 0) {
      item.Options.forEach((option) => {
        this.dic.push(option);
      });
      //this.dic = item.Options;
    } else {
      let r = await this.dataService.getDic(item);
      r.forEach((v) => this.dic.push(v));
    }
    console.log(this.dic);
  }

  showResult(item) {
    item.showResult = true;
  }
  hideResult(item) {
    item.showResult = false;
  }

  selectValues() {
    console.log(this.currentitem);
    console.log(this.selectitemValue);
    console.log(this.currentitem);
    if (this.selectitemValue.length > 0) {
      this.currentitem.Value = this.selectitemValue[0];
      this.currentitem.Value = '';
      this.currentitem.Value = this.selectitemValue
        .map((v) => v[Object.keys(v)[0]])
        .join(',');
    }
    this.showselect = false;
  }

  earliest: any = undefined;
  queryName: string;
  queryAuthor: string;
  async search() {
    console.log('load click');
    let rl = await this.dataService.getModel(
      this.storeService.loginUser.UserName,
      undefined,
      this.earliest,
      this.queryName,
      this.queryAuthor
    );
    for (let index = 0; index < rl.length; index++) {
      const element = rl[index];
      element['publicCondition'] = this.dataService.getPublicCondition(element);
      element['version'] = this.dataService.getPackageVersion(element);
    }
    this.storeService.modelList = rl;
  }
}
